﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Codeflows;
using Codeflows.Results;
using Codeflows.Tracking;

namespace CodeflowsTests
{
    public static class CodeflowExecutionHelpers
    {
        public static CodeflowRunResult<T> ThenResume<T>(this CodeflowRunResult<T> runResult,
                                                         Expression<Func<T, Result>> action) where T : Codeflow
        {
            var newResult = runResult.Codeflow.Resume(runResult.CodeflowId, action);
            return new CodeflowRunResult<T>(runResult.TrackerFactory, runResult.Codeflow, runResult.CodeflowId, newResult);
        }

        public static CodeflowRunResult<T> AfterAllPendings<T>(this CodeflowRunResult<T> runResult) where T : Codeflow
        {            
            var result = runResult.Result;
            while (result.IsPending)
            {
                var pendingResult = (PendingResult) result;
                pendingResult.PendingTask.Wait();                
                result = pendingResult.PendingTask.Result;
            }

            return new CodeflowRunResult<T>(runResult.TrackerFactory, runResult.Codeflow, runResult.CodeflowId, result);
        }

        public static CodeflowAction CurrentAction<T>(this CodeflowRunResult<T> runResult)
            where T : Codeflow
        {
            return runResult.PersistedInstance.CurrentAction;
        }
    }
}